from vm_test import someProcessDetailed
import time
from configparser import ConfigParser
import cv2
import numpy as np
import sys
from collections import deque
import random

def thinImage(src, maxIterations=-1):
    assert len(src.shape) == 2, 'please binarify pictures'
    img_height, img_width = src.shape
    dst = src.copy()
    count = 0
    while True:
        count +=1
        if maxIterations != -1 and count > maxIterations:
            break
        mFlag = []
        for i in range(img_height):
            for j in range(img_width):
                p1 = dst[i, j]
                if p1 != 1:
                    continue
                p4 = 0 if j == img_width-1 else dst[i, j+1]
                p8 = 0 if j == 0 else dst[i, j-1]
                p2 = 0 if i == 0 else dst[i-1, j]
                p3 = 0 if i == 0 or j == img_width-1 else dst[i-1, j+1]
                p9 = 0 if i == 0 or j == 0 else dst[i-1, j-1]
                p6 = 0 if i == img_height-1 else dst[i+1, j]
                p5 = 0 if i == img_height-1 or j == img_width-1 else dst[i+1, j+1]
                p7 = 0 if i == img_height-1 or j == 0 else dst[i+1, j-1]
                if p2+p3+p4+p5+p6+p7+p8+p9>=2 and p2+p3+p4+p5+p6+p7+p8+p9<=6:
                    ap = 0
                    if p2 == 0 and p3 ==1:
                        ap+=1
                    if p3 == 0 and p4 == 1:
                        ap+=1
                    if p4 ==0 and p5 == 1:
                        ap+=1
                    if p5 == 0 and p6 == 1:
                        ap+=1
                    if p6 == 0 and p7 == 1:
                        ap+=1
                    if p7 == 0 and p8 == 1:
                        ap+=1
                    if p8 == 0 and p9 == 1:
                        ap+=1
                    if p9 == 0 and p2 == 1:
                        ap+=1
                    if ap == 1 and p2*p4*p6 == 0 and p4*p6*p8 == 0:
                        mFlag.append([i, j])
        for flag in mFlag:
            dst[flag[0], flag[1]] = 0
        if len(mFlag) == 0:
            break
        else:
            mFlag.clear()
        for i in range(img_height):
            for j in range(img_width):
                p1 = dst[i, j]
                if p1 != 1:
                    continue
                p4 = 0 if j == img_width-1 else dst[i, j+1]
                p8 = 0 if j == 0 else dst[i, j-1]
                p2 = 0 if i == 0 else dst[i-1, j]
                p3 = 0 if i == 0 or j == img_width-1 else dst[i-1, j+1]
                p9 = 0 if i == 0 or j == 0 else dst[i-1, j-1]
                p6 = 0 if i == img_height-1 else dst[i+1, j]
                p5 = 0 if i == img_height-1 or j == img_width-1 else dst[i+1, j+1]
                p7 = 0 if i == img_height-1 or j == 0 else dst[i+1, j-1]
                if p2+p3+p4+p5+p6+p7+p8+p9>=2 and p2+p3+p4+p5+p6+p7+p8+p9<=6:
                    ap = 0
                    if p2 == 0 and p3 ==1:
                        ap+=1
                    if p3 == 0 and p4 == 1:
                        ap+=1
                    if p4 ==0 and p5 == 1:
                        ap+=1
                    if p5 == 0 and p6 == 1:
                        ap+=1
                    if p6 == 0 and p7 == 1:
                        ap+=1
                    if p7 == 0 and p8 == 1:
                        ap+=1
                    if p8 == 0 and p9 == 1:
                        ap+=1
                    if p9 == 0 and p2 == 1:
                        ap+=1
                    if ap == 1 and p2*p4*p8 == 0 and p2*p6*p8 == 0:
                        mFlag.append([i, j])
        for flag in mFlag:
            dst[flag[0], flag[1]] = 0
        if len(mFlag) == 0:
            break
        else:
            mFlag.clear()
    return dst

def findNextPoint(neighbor_points, image, inpoint, flag):
    i = flag
    count = 1
    success = False
    img_height, img_width = image.shape[:2]
    outpoint = (0, 0)
    outflag = 0
    while count <= 8:
        tmppoint_r = inpoint[0]+neighbor_points[i][0]
        tmppoint_c = inpoint[1]+neighbor_points[i][1]
        if tmppoint_r > 0 and tmppoint_c > 0 and tmppoint_c < img_width and tmppoint_r < img_height:
            if image[tmppoint_r, tmppoint_c] == 255:
                outpoint = (tmppoint_r, tmppoint_c)
                outflag = i
                success = True
                image[tmppoint_r, tmppoint_c] = 0
                break
        if count%2:
            i+=count
            if i > 7:
                i-=8
        else:
            i+=-count
            if i < 0:
                i+=8
        count+=1
    return success, outpoint, outflag
#point 的坐标是（行数，列数）的意思
def findFirstPoint(inputimg):
    success = False
    outputpoint = (0, 0)
    img_height, img_width = inputimg.shape[:2]
    for i in range(img_height):
        for j in range(img_width):
            if inputimg[i, j] == 255:
                success = True
                outputpoint = (i, j)
                inputimg[i, j] = 0
                break
        if success:
            break
    return success, outputpoint

def findLines(inputimg):
    neighbor_points=[[-1, -1], [0, -1], [1, -1], [1, 0], [1, 1], [0, 1], [-1, 1], [-1, 0]]
    success, firstpoint = findFirstPoint(inputimg)
    lines = []
    while success:
        line = deque([])
        line.append(firstpoint)
        this_point = firstpoint
        this_flag = 0
        success, next_point, next_flag = findNextPoint(neighbor_points, inputimg, this_point, this_flag)
        while success:
            line.append(next_point)
            this_point = next_point
            this_flag = next_flag
            success, next_point, next_flag = findNextPoint(neighbor_points, inputimg, this_point, this_flag)
        this_point = firstpoint
        this_flag = 0
        success, next_point, next_flag = findNextPoint(neighbor_points, inputimg, this_point, this_flag)
        while success:
            line.appendleft(next_point)
            this_point = next_point
            this_flag = next_flag
            success, next_point, next_flag = findNextPoint(neighbor_points, inputimg, this_point, this_flag)
        if len(line) > 10:
            lines.append(line)
        success, firstpoint = findFirstPoint(inputimg)
    return lines

if __name__ == '__main__':
    startTime = time.time()
    cfg = ConfigParser()
    cfg.read('SWQT.ini')
    files = ['C:/Users/tellw/Desktop/bishe/items/calibed_pics/20200326101821left/0.jpg', 'C:/Users/tellw/Desktop/bishe/items/calibed_pics/20200326101821right/0.jpg']
    #files = ['C:/Users/tellw/Desktop/toSkeleton.png', 'C:/Users/tellw/Desktop/1.png']
    for file in files:
        img = cv2.imread(file, 0)
        img = someProcessDetailed(img, cfg, bGaussianBlur=1, bCanny=1)
        img_copy = img.copy()
        _, img = cv2.threshold(img, 128, 1, cv2.THRESH_BINARY)
        img = thinImage(img)
        img[img==1] = 255
        lines = findLines(img)
        # cv2.imshow('%s lines'%file, img)
        img = cv2.cvtColor(img, cv2.COLOR_GRAY2BGR)
        for line in lines:
            color = random.sample(range(256), 3)
            for pix in line:
                img[pix] = color
        cv2.imshow('%s after line-finding'%file, img)
        # cv2.imshow('%s after process copied'%file, img_copy)
    print('running %f s'%(time.time()-startTime))
    cv2.waitKey()
    cv2.destroyAllWindows()